import json
import os
from pathlib import Path
from PIL import Image, ImageTk
import tkinter as tk

class ResourceManager:
    def __init__(self, assets_root=None):
        self.assets_root = Path(assets_root) if assets_root else None
        self.texture_cache = {}
        self.animation_cache = {}
        self.texture_size = 32
        
    def set_assets_root(self, path):
        """设置资源根目录"""
        self.assets_root = Path(path)
        print(f"设置资源根目录: {self.assets_root}")
        
    def resolve_texture_path(self, item_id, texture_type="items"):
        """解析纹理路径 - 改进的版本，支持压缩包"""
        if not self.assets_root:
            # 如果没有设置资源根目录，使用默认资源路径
            default_path = Path(__file__).parent.parent / "resources" / "minecraft" / "textures" / texture_type
            if default_path.exists():
                self.assets_root = default_path.parent.parent.parent
            else:
                return None
        
        # 清理物品ID
        if ':' in item_id:
            item_id = item_id.split(':')[1]
            
        print(f"查找物品: {item_id}, 资源根目录: {self.assets_root}")
        
        # 查找纹理文件 - 改进的路径顺序，优先查找压缩包内的资源
        possible_paths = [
            # 1. 在资源根目录的textures文件夹中查找
            self.assets_root / "textures" / texture_type / f"{item_id}.png",
            # 2. 在资源根目录的items文件夹中直接查找
            self.assets_root / texture_type / f"{item_id}.png",
            # 3. 在项目资源目录中查找
            Path(__file__).parent.parent / "resources" / "minecraft" / "textures" / texture_type / f"{item_id}.png",
            # 4. 在资源根目录中直接查找
            self.assets_root / f"{item_id}.png",
        ]
        
        for path in possible_paths:
            print(f"检查路径: {path}")
            if path.exists():
                print(f"找到纹理: {path}")
                return path
                
        print(f"未找到纹理: {item_id}")
        return None
        
    def load_texture(self, item_id, texture_type="items"):
        """加载纹理"""
        cache_key = f"{item_id}_{texture_type}"
        
        if cache_key in self.texture_cache:
            return self.texture_cache[cache_key]
            
        texture_path = self.resolve_texture_path(item_id, texture_type)
        
        if not texture_path:
            # 加载错误纹理
            print(f"使用错误纹理替代: {item_id}")
            error_texture = self._load_error_texture()
            self.texture_cache[cache_key] = error_texture
            return error_texture
            
        # 检查是否有动画配置
        anim_config = self._load_animation_config(texture_path)
        
        if anim_config:
            # 动态纹理
            texture = self._load_animated_texture(texture_path, anim_config)
        else:
            # 静态纹理
            texture = self._load_static_texture(texture_path)
            
        self.texture_cache[cache_key] = texture
        return texture
        
    def _load_animation_config(self, texture_path):
        """加载动画配置文件"""
        anim_path = texture_path.with_suffix('.png.mcmeta')
        
        if not anim_path.exists():
            return None
            
        cache_key = str(anim_path)
        if cache_key in self.animation_cache:
            return self.animation_cache[cache_key]
            
        try:
            with open(anim_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                
            anim_config = config.get('animation', {})
            # 使用默认配置
            final_config = {
                "frametime": 1,
                "interpolate": False,
                "frames": []
            }
            final_config.update(anim_config)
            
            self.animation_cache[cache_key] = final_config
            return final_config
            
        except Exception as e:
            print(f"加载动画配置失败 {anim_path}: {e}")
            return None
            
    def _load_static_texture(self, texture_path):
        """加载静态纹理"""
        try:
            image = Image.open(texture_path)
            print(f"加载纹理: {texture_path}, 尺寸: {image.size}")
            
            # 调整到标准尺寸
            if image.size != (self.texture_size, self.texture_size):
                print(f"调整纹理尺寸: {image.size} -> ({self.texture_size}, {self.texture_size})")
                image = image.resize((self.texture_size, self.texture_size), Image.LANCZOS)
                
            return ImageTk.PhotoImage(image)
        except Exception as e:
            print(f"加载纹理失败 {texture_path}: {e}")
            return self._load_error_texture()
            
    def _load_animated_texture(self, texture_path, anim_config):
        """加载动态纹理"""
        try:
            image = Image.open(texture_path)
            frame_time = anim_config.get('frametime', 1)
            frames_data = anim_config.get('frames', [])
            
            print(f"加载动态纹理: {texture_path}, 总尺寸: {image.size}")
            
            # 计算帧信息
            frame_width, frame_height = image.size
            frame_count = frame_height // frame_width
            
            print(f"帧数: {frame_count}, 帧宽度: {frame_width}")
            
            if frames_data:
                # 自定义帧顺序
                frames = []
                for frame_index in frames_data:
                    if isinstance(frame_index, dict):
                        frame_index = frame_index.get('index', 0)
                    y = frame_index * frame_width
                    frame = image.crop((0, y, frame_width, y + frame_width))
                    frame = frame.resize((self.texture_size, self.texture_size), Image.LANCZOS)
                    frames.append(ImageTk.PhotoImage(frame))
            else:
                # 顺序帧
                frames = []
                for i in range(frame_count):
                    y = i * frame_width
                    frame = image.crop((0, y, frame_width, y + frame_width))
                    frame = frame.resize((self.texture_size, self.texture_size), Image.LANCZOS)
                    frames.append(ImageTk.PhotoImage(frame))
                    
            return {
                'frames': frames,
                'frame_time': frame_time,
                'current_frame': 0,
                'animated': True
            }
            
        except Exception as e:
            print(f"加载动态纹理失败 {texture_path}: {e}")
            return self._load_error_texture()
            
    def _load_error_texture(self):
        """加载错误纹理"""
        print("创建错误纹理")
        # 创建错误纹理
        image = Image.new('RGB', (self.texture_size, self.texture_size))
        pixels = image.load()
        
        for x in range(self.texture_size):
            for y in range(self.texture_size):
                if (x // (self.texture_size // 2) + y // (self.texture_size // 2)) % 2 == 0:
                    pixels[x, y] = (255, 0, 255)  # 品红色
                else:
                    pixels[x, y] = (0, 0, 0)      # 黑色
                    
        return ImageTk.PhotoImage(image)
        
    def cleanup(self):
        """清理资源"""
        self.texture_cache.clear()
        self.animation_cache.clear()